package co.yixiang.modules.auction.service.impl;

import co.yixiang.utils.RedisUtils;
import lombok.AllArgsConstructor;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@AllArgsConstructor
//@CacheConfig(cacheNames = "yxAuctionOrder")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@RestController
public class TestAuction {

    private final RedisUtils redisUtil;

    @RequestMapping("/test")
    public void testRedis() throws InterruptedException {
        redisUtil.set("tete","我是你爸爸");

        int totalThreads = 2000;
        ExecutorService executorService = Executors.newFixedThreadPool(totalThreads);

        CountDownLatch countDownLatch = new CountDownLatch(totalThreads);
        for(int i=0; i<totalThreads; i++) {
            String threadId = String.valueOf(i);
            executorService.execute( () -> {
                try {
                    testLock("tate", threadId);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        // After all thread done, acquire again, expect to be successful.
        testLock("tate", "final success");
    }

    public void testLock(String key, String threadId) throws InterruptedException {
//        if(threadId.equals("500")){
//            Thread.sleep(6000);
//        }
        boolean lock = redisUtil.lock(key);
        if (lock) {
            String value = redisUtil.get("tete").toString();
            System.out.println(threadId);
//            Thread.sleep(5000);
            redisUtil.delete(key);
        } else {
            System.out.println("value");
        }
    }
}
